package demo.android.myapplication.demos.touch

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PointF
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.MotionEvent.*
import android.view.View
import cn.android.basic.decodeBitmap
import cn.android.basic.dp
import cn.android.basic.int
import demo.android.myapplication.R

/**
 * Created by guoshiwen on 2021/7/27.
 */
class MultiPointView2 @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val source = decodeBitmap(R.mipmap.ic_launcher_copy, 200.dp.int)
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var offsetX = 0f
    private var offsetY = 0f
    private val focus = PointF()

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawBitmap(source, offsetX, offsetY, paint)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when(event.actionMasked) {
            ACTION_DOWN, ACTION_POINTER_DOWN -> {
                updateFocus(event)
            }
            ACTION_MOVE -> {
                val downX = focus.x
                val downY = focus.y

                updateFocus(event)

                offsetX += focus.x - downX
                offsetY += focus.y - downY

                invalidate()
            }
            ACTION_POINTER_UP -> {
                updateFocus(event, event.actionIndex)
            }
        }
        return true
    }

    private fun updateFocus(event: MotionEvent, excludeIndex: Int = -1) {
        var sumX = 0f
        var sumY = 0f
        var count = event.pointerCount
        for (i in 0 until event.pointerCount) {
            if(excludeIndex != -1 && excludeIndex < event.pointerCount && i == excludeIndex){
                count--
                continue
            }

            sumX += event.getX(i)
            sumY += event.getY(i)
        }
        focus.set(sumX / count, sumY / count)
    }
}